<?php
require_once('classes/config.inc.php');
require_once(DIR_CLASS. 'Session.php');
require_once(DIR_CLASS. 'Database.php');
include(DIR_CLASS. 'TemplateParser.php');

$session = new UserSession();
$session->open();

$db = new MYSQLDatabase(DB_SERVER,DB_USER,DB_PASS,DB_DATABASE);
try {
		$db->connect();
}catch (Exception $e){
		echo $e->getMessage();
}
$sql = "SELECT * FROM ". TABLE_JOBS ." WHERE(finished='0' AND deadline>NOW()) ORDER BY `Job`.`deadline` ASC  LIMIT 0 , 5";
$new_jobs = "";
$link = $db->query($sql);
$now = time();
function getTimeBetween($time,$other_time){
	$vers = strtotime($time)-strtotime($other_time);
	$res="";
	if($vers>60*60*24*2){
		$res .= (int)($vers/(60*60*24))." days ";
		$vers = $vers%(60*60*24);
	}
	if($vers>60*60*24){
		$res .= (int)($vers/(60*60*24))." day ";
		$vers = $vers%(60*60*24);
	}
	if($vers>60*60*2){
		$res .= (int)($vers/(60*60))." hours ";
		$vers = $vers%(60*60);
	}
	if($vers>60*60){
		$res .= (int)($vers/(60*60))." hour ";
		$vers = $vers%(60*60);
	}
	if($vers>60*2){
		$res .= (int)($vers/(60*60))." mins ";
		$vers = $vers%(60);
	}
	if($vers>60){
		$res .= (int)($vers/(60*60))." min ";
		$vers = $vers%(60);
	}
	return $res;
}
if(mysql_num_rows($link)>0){
	while($res = mysql_fetch_array($link)){
		$new_jobs .= "<tr>
					<td class=\"jobType\"><a href=\"jobs.php?job=".$res["id"]."\">".$res["title"]."</a></td>
					<td>".getTimeBetween($res["deadline"],$now)."</td>
				</tr>";
	}
}
else{
	$new_jobs = "No jobs at the moment.";
}

$sql = "SELECT title,id FROM ". TABLE_CAT ." ORDER BY title ASC LIMIT 0, 20";
$cats = "";
$link = $db->query($sql);
if(mysql_num_rows($link)>0){
	while($res = mysql_fetch_array($link)){
		$cats .= "<li><a href=\"jobs.php?cat=".$res["id"]."\">". $res["title"] ."</a></li>";
	}
}
else{
	$error = "No cats at the moment.";
}
$template_array = array(
	"URGENT_JOBS" => $new_jobs,
	"CATS" => $cats
);
	
$template = new TemplateParser();
$template->loadfile("templates/index.tpl");
$template->assignVars($template_array);
$template->output();
?>